<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        v-waves
        class="el-button filter-item el-button--primary el-button--medium"
        type="primary"
      >好评数({{ carTotal.goodComment }})</el-button>
      <el-button
        v-waves
        class="el-button filter-item el-button--primary el-button--medium"
        type="primary"
      >中评数({{ carTotal.middleComment }})</el-button>
      <el-button
        v-waves
        class="el-button filter-item el-button--primary el-button--medium"
        type="primary"
      >差评数({{ carTotal.badComment }})</el-button>
    </div>
    <div class="filter-container" style="padding: 16px 0;">
      <!-- <el-input v-model="listQuery.driverName" placeholder="司机" style="width: 200px;" class="filter-item el-input--medium" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.ownerName" placeholder="货主" style="width: 200px;" class="filter-item el-input--medium" @keyup.enter.native="handleFilter" />-->

      <el-input
        v-model="search.phone"
        placeholder="手机号码"
        style="width: 200px;"
        class="filter-item el-input--medium"
        @keyup.enter.native="searchList"
      />
      <el-input
        v-model="search.nickname"
        placeholder="昵称"
        style="width: 200px;"
        class="filter-item el-input--medium"
        @keyup.enter.native="searchList"
      />
      <!-- <el-select v-model="listQuery.importance" placeholder="Imp" clearable style="width: 90px" class="filter-item">
        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="listQuery.type" placeholder="Type" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>-->
      <el-button
        v-waves
        class="el-button filter-item el-button--primary el-button--medium"
        type="primary"
        icon="el-icon-search"
        @click="searchList"
      >搜索</el-button>
      <!-- <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        Add
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        Export
      </el-button>
      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        reviewer
      </el-checkbox>-->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column
        label="编号"
        width="150"
        align="center"
      >
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center">
        <template slot-scope="{row}">
          <span>{{ row.nickname }}</span>
          <!-- <el-tag>{{ row.ownerName  }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column label="电话" align="center" width="110">
        <template slot-scope="{row}">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="车牌号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.carNumber }}</span>
          <!-- <el-tag>{{ row.ownerName  }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column label="身份证号码" align="center" width="185">
        <template slot-scope="{row}">
          <span>{{ row.idCardNumber }}</span>
          <!-- <el-tag>{{ row.ownerName  }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column label="订单数" align="center">
        <template slot-scope="{row}">
          <span>{{ row.orderTotalNumber }}</span>
        </template>
      </el-table-column>

      <el-table-column label="好评" align="center">
        <template slot-scope="{row}">
          <span>{{ row.goodCommentTotal }}</span>
        </template>
      </el-table-column>
      <el-table-column label="好评率" align="center">
        <template slot-scope="{row}">
          <span>{{ row.goodCommentRate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="中评" align="center">
        <template slot-scope="{row}">
          <span>{{ row.middleCommentTotal }}</span>
        </template>
      </el-table-column>
      <el-table-column label="差评" align="center">
        <template slot-scope="{row}">
          <span>{{ row.badCommentTotal }}</span>
        </template>
      </el-table-column>

      <el-table-column label="推广数" align="center">
        <template slot-scope="{row}">
          <span>{{ row.vehicleVolume }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column v-if="showReviewer" label="Reviewer" width="110px" align="center">
        <template slot-scope="{row}">
          <span style="color:red;">{{ row.reviewer }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Imp" width="80px">
        <template slot-scope="{row}">
          <svg-icon v-for="n in + row.importance" :key="n" icon-class="star" class="meta-item__icon" />
        </template>
      </el-table-column>
      <el-table-column label="Readings" align="center" width="95">
        <template slot-scope="{row}">
          <span v-if="row.pageviews" class="link-type" @click="handleFetchPv(row.pageviews)">{{ row.pageviews }}</span>
          <span v-else>0</span>
        </template>
      </el-table-column>
      <el-table-column label="Status" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>-->
      <!-- <el-table-column
        label="操作"
        width="220"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{row}">
          <el-button size="mini" @click="openDetail(row.id)">详情</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
         <el-button v-if="row.status!='published'" size="mini" type="success" @click="handleModifyStatus(row,'published')">
            Publish
          </el-button>
          <el-button v-if="row.state!='-2'" size="mini" type="danger" @click="stopCar(row.id)">停用</el-button>
          <el-button v-if="row.state=='-2'" size="mini" type="success" @click="backCar(row.id)">恢复</el-button>
          <el-button v-if="row.state=='-2'" size="mini" type="danger" @click="deleteCar(row.id)">删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limt.sync="listQuery.pageSize"
      @pagination="getList"
    />

  </div>
</template>

<script>
import {
  fetchCommentList,
  fetchPv,
  createArticle,
  updateArticle,
  getCommentTotal,
  commentSearch,
  stopCar,
  backCar,
  getDriverDetail,
  getDriverOrderList
  // createObjectURL
} from '@/api/driver'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import '../../styles/car.scss'
const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

const orderStateDate = []
orderStateDate[-1] = '货主取消订单'
orderStateDate[-2] = '货主申请取消订单'
orderStateDate[-4] = '司机取消订单'
orderStateDate[0] = '待接货'
orderStateDate[1] = '已接单'
orderStateDate[2] = '已装货'
orderStateDate[3] = '待发货'
orderStateDate[4] = '待收货'
orderStateDate[5] = '已达到'
orderStateDate[6] = '已完成'

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    },
    parseTime: parseTime,
    orderState(type) {
      return orderStateDate[type]
    },
    usertype(type) {
      const usertype = []
      usertype[1] = '司机'
      usertype[2] = '货主'
      return usertype[type]
    }
  },
  data() {
    return {
      header: {
        'consumes': 'multipart/form-data',
        'token': getToken()
      },
      objectBind: null,
      dialogTableVisible: false,
      tableKey: 0,
      list: null,
      carTotal: {
        middleComment: 0,
        badComment: 0,
        goodComment: 0
      },
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        importance: undefined,
        title: undefined,
        state: undefined,
        orderId: undefined,
        driverName: undefined

        // sort: '+id'
      },
      search: {
        nickname: '',
        phone: '',
        pageNum: 1,
        pageSize: 20
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [
        { label: 'ID Ascending', key: '+id' },
        { label: 'ID Descending', key: '-id' }
      ],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        type: '',
        status: 'published'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [
          { required: true, message: 'type is required', trigger: 'change' }
        ],
        timestamp: [
          {
            type: 'date',
            required: true,
            message: 'timestamp is required',
            trigger: 'change'
          }
        ],
        title: [
          { required: true, message: 'title is required', trigger: 'blur' }
        ]
      },
      downloadLoading: false,
      gridData: [],
      gridListTotal: {
        pageNum: 1,
        pageSize: 20,
        totalRow: 0
      },
      driverData: {
        attachAuthState: '',
        idAuthState: '',
        jobAuthState: '',
        licenceAuthState: '',
        pictures: {
          intoImg: '',
          jobImg: '',
          patenteImg: '',
          drivingImg: '',
          idCardImgF: '',
          idCardImgB: '',
          leftImg: '',
          reverseImg: '',
          rightImg: '',
          vehicleImg: ''
        }
      },
      editDriver: {
        headImg: ''
      },
      driverTotalData: [
        {
          income: 0,
          orderTotal: 0,
          commentTotal: 0
        }
      ]
    }
  },
  created() {
    this.getCommentTotal()
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchCommentList(this.listQuery).then(response => {
        console.log(response.result)
        this.list = response.result
        this.total = response.page.totalRow

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    getCommentTotal() {
      this.listLoading = true
      getCommentTotal().then(response => {
        this.carTotal = response.result
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter(typeDate) {
      if (!isNaN(typeDate)) {
        console.log('sss' + typeDate)
        this.listQuery.state = typeDate
      } else {
        console.log(typeDate)
        this.listQuery.state = ''
      }
      const arr = this.listQuery
      for (const key in arr) {
        // 去除对象内多余的空值key
        if (arr[key] === '') {
          delete arr[key]
        }
      }
      this.listQuery = arr
      this.listQuery.pageNum = 1
      this.getList()
    },
    // 搜索更新列表
    searchList() {
      this.listLoading = true
      commentSearch(this.search).then(response => {
        console.log(response.result)
        this.list = response.result
        // this.total = response.page.totalRow

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    openDetail(id) {
      console.log(id)
      // var dialogTableVisible = !this.dialogTableVisible
      this.dialogTableVisible = !this.dialogTableVisible
      getDriverDetail(id).then(response => {
        this.driverData = response.result
        this.editDriver = response.result
        this.driverTotalData[0].income = response.result.income
        this.driverTotalData[0].orderTotal = response.result.orderTotal
        this.driverTotalData[0].commentTotal = response.result.commentTotal
        this.getDriverOrderList(id)
        console.log(this.driverTotalData)
        console.log(response)
      })
    },
    getDriverOrderList(id) {
      getDriverOrderList(id).then(response2 => {
        console.log(response2)
        this.gridData = response2.result
        this.gridListTotal = response2.page
      })
      console.log(this.gridListTotal)
    },
    stopCar(id) {
      this.listLoading = true

      stopCar(id).then(response => {
        console.log(response.result)
        this.getCommentTotal()
        this.getList()

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },

    backCar(id) {
      this.listLoading = true
      backCar(id).then(response => {
        console.log(response.result)
        this.getCommentTotal()
        this.getList()

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          this.temp.author = 'vue-element-admin'
          createArticle(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      console.log(this.editDriver)
      // if (this.editDriver.headImg1) {
      //   this.editDriver.headImg = parseInt(this.editDriver.headImg1)
      // }
      // if (this.editDriver.idCardImgF1) {
      //   this.editDriver.idCardImgF = parseInt(this.editDriver.idCardImgF1)
      // }
      // if (this.editDriver.idCardImgB1) {
      //   this.editDriver.idCardImgB = parseInt(this.editDriver.idCardImgB1)
      // }
      updateArticle(this.editDriver).then(response => {
        this.$notify({
          title: '编辑成功',
          message: '编辑成功',
          type: 'success',
          duration: 2000
        })
        this.dialogTableVisible = false
        this.getCommentTotal()
        this.getList()
      })
    },
    handleDelete(row) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          'timestamp',
          'orderNo',
          'type',
          'importance',
          'status'
        ]
        const filterVal = [
          'timestamp',
          'orderNo',
          'type',
          'importance',
          'status'
        ]
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : sort === `-${key}` ? 'descending' : ''
    },
    handleAvatarSuccess(res, file) {
      // this.editDriver.headImg1 = res.result.id
      console.log(this.editDriver)
      this.driverData.headImg = res.result.fileUrl
      this.editDriver.headImg = res.result.fileUrl
      // this.imageUrl = createObjectURL(file.raw)
    },
    handleIdCardImgBSuccess(res, file) {
      // this.editDriver.pictures.idCardImgB1 = res.result.id
      console.log(this.editDriver)
      this.driverData.pictures.idCardImgB = res.result.fileUrl
      this.editDriver.pictures.idCardImgB = res.result.fileUrl
      // this.imageUrl = createObjectURL(file.raw)
    },
    handleIdCardImgFSuccess(res, file) {
      // this.editDriver.pictures.idCardImgF1 = res.result.id
      console.log(this.editDriver)
      this.driverData.pictures.idCardImgF = res.result.fileUrl
      this.editDriver.pictures.idCardImgF = res.result.fileUrl
      // this.imageUrl = createObjectURL(file.raw)
    },
    handleDrivingImgSuccess(res, file) {
      console.log(this.editDriver)
      this.driverData.pictures.idCardImgF = res.result.fileUrl
      this.editDriver.pictures.idCardImgF = res.result.fileUrl
    },
    handlePatenteImgSuccess(res, file) {
      console.log(this.editDriver)
      this.driverData.pictures.patenteImg = res.result.fileUrl
      this.editDriver.pictures.patenteImg = res.result.fileUrl
    },
    handleJobImgSuccess(res, file) {
      console.log(this.editDriver)
      this.driverData.pictures.jobImg = res.result.fileUrl
      this.editDriver.pictures.jobImg = res.result.fileUrl
    },
    handleIntoImgSuccess(res, file) {
      console.log(this.editDriver)
      this.driverData.pictures.intoImg = res.result.fileUrl
      this.editDriver.pictures.intoImg = res.result.fileUrl
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>
<style>
.tableTitle {
  width: 150px;
  padding-right: 20px;
  text-align: right;
  font-weight: bold;
}
.authTable tr{
  height: 50px;
}
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    display: block;
  }
</style>
